<?php
namespace app\index\controller;
use think\Db;
use think\Controller;
use think\Url;
class Nearstore extends Controller{
    public function index(){
        return $this->fetch('nearstore/nearstore');
    }
    public function nearstore(){
        $queryIP = $_SERVER['REMOTE_ADDR'];
        $url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$queryIP;
        //curl_setopt($ch,CURLOPT_ENCODING ,'utf8');
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
        $location = curl_exec($ch);
        $location = json_decode($location);
        $loc = "";
        if($location===FALSE) return "";
        if (empty($location->desc)) {
            $loc = $location->province.$location->city.$location->district.$location->isp;
        }else{
            $loc = $location->desc;
        }
        $loc1 = mb_substr($loc,2,2);
        $loc1 = $loc1.'市';
        $url = file_get_contents("http://api.map.baidu.com/geocoder/v2/?address=".$loc1."&output=json&ak=KPcmVPcAwULwmdMnLKAbLsvE6FSYGXGm");
        //获取输入地址的经纬度
        $a = strstr($url,'lng');
        $lng1 = substr($a,5,15);
        $b = strstr($url,'lat');
        $lat1 = substr($b,5,9);
        //获取数据库地址的经纬度
//        $lng2 = 120.21937541572;
//        $lat2 = 31.259244;
        $field = [
            'logo_img',
            'name',
            'id',
            'address',
            'like',
            'lng',
            'lat'
        ];
        $addr = Db::name('store_unline')->where('status',1)->field($field)->select();
        $res = array();
        for($i=0;$i<count($addr);$i++){
            $lng2 = $addr[$i]['lng'];
            $lat2 = $addr[$i]['lat'];
            /// <summary>
            /// 获取两个经纬度之间的距离
            /// </summary>
            /// <param name="LonA">经度A</param>
            /// <param name="LatA">纬度A</param>
            /// <param name="LonB">经度B</param>
            /// <param name="LatB">经度B</param>
            /// <returns>距离（千米）</returns>
            // 地球半径（千米）
            $R = 6371.004;
            $C = sin($lat1* M_PI / 180.0) * sin($lat2* M_PI / 180.0) + cos($lat1* M_PI / 180.0) * cos($lat2* M_PI / 180.0) * cos(($lng1 - $lng2)* M_PI / 180.0);
            //两点之间的距离
            $juli =$R * acos($C);
            if($juli<50){
                $juli = (int)(1000*$juli);
                $addr[$i]['distance'] = $juli;
                $res[] = $addr[$i];
            }
        }
        if(!empty($res)){
            return format_return(1,$res,'数据获取成功');
        }else{
            return format_return(0,'','数据为空');
        }

    }

}
